// 运行时配置
import type { Settings as LayoutSettings } from '@ant-design/pro-components';
import { ProConfigProvider, SettingDrawer } from '@ant-design/pro-components';
import type { RequestConfig, RunTimeLayoutConfig } from '@umijs/max';
import { history } from '@umijs/max';
import { ConfigProvider, Spin, message, theme } from 'antd';
import './app.less';
import Footer from './components/Footer';
import { AvatarDropdown } from './components/RightContent/AvatarDropdown';
import Schema from './components/Schema';
import * as api from './services/api';
const loginPath = '/login';

// APP 初始状态
export interface AppInitialState {
  settings?: Partial<LayoutSettings>;
  currentUser?: Api.UserInfo;
  fetchUserInfo?: () => Promise<Api.UserInfo | undefined>;
  loading: boolean;
  title?: string | false;
}
// 全局初始化数据配置，用于 Layout 用户信息和权限初始化
// 更多信息见文档：https://umijs.org/docs/api/runtime-config#getinitialstate
export async function getInitialState(): Promise<AppInitialState> {
  let currentUser = undefined;
  const fetchUserInfo = async () => {
    try {
      const res = await api.currentUser();
      return res.data;
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };
  currentUser = await fetchUserInfo();
  return {
    loading: false,
    title: '快诺优商城',
    currentUser,
    fetchUserInfo,
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({
  initialState,
  setInitialState,
}) => {
  let title = '快诺优商城';
  let logo = null;
  if (initialState?.currentUser?.company) {
    title = initialState?.currentUser?.company.name;
    logo = initialState?.currentUser?.company.mini_program_logo;
  }

  return {
    title,
    logo,
    avatarProps: {
      // src: initialState?.currentUser?.avatar,
      src: 'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png',
      size: 'small',
      title: initialState?.currentUser?.username,
      render: (props, dom) => {
        return <AvatarDropdown>{dom}</AvatarDropdown>;
      },
    },
    footerRender: () => <Footer />,

    // waterMarkProps: {
    //   content: initialState?.currentUser?.username,
    // },
    onPageChange: () => {
      const { location } = history;
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && location.pathname !== loginPath) {
        history.push(loginPath);
      }
    },
    layoutBgImgList: [
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/D2LWSqNny4sAAAAAAAAAAAAAFl94AQBr',
        left: 85,
        bottom: 100,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/C2TWRpJpiC0AAAAAAAAAAAAAFl94AQBr',
        bottom: -68,
        right: -45,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/F6vSTbj8KpYAAAAAAAAAAAAAFl94AQBr',
        bottom: 0,
        left: 0,
        width: '331px',
      },
    ],
    loading: initialState?.loading,
    layout: 'mix',
    childrenRender: (children) => {
      // if (initialState?.loading) return <PageLoading />;
      const themeConfig = {
        token: {
          borderRadius: 4,
        },
        algorithm: [theme.compactAlgorithm],
        component: {
          Modal: {
            titleFontSize: 14,
            titleLineHeight: 2,
          },
        },
      };
      return (
        <ProConfigProvider valueTypeMap={Schema as Record<string, any>}>
          <ConfigProvider theme={themeConfig} componentSize={'small'}>
            {children}
            <SettingDrawer
              disableUrlParams
              enableDarkTheme
              settings={initialState?.settings}
              onSettingChange={(settings) => {
                setInitialState((preInitialState) => ({
                  ...preInitialState,
                  loading: false,
                  settings,
                }));
              }}
            />
            <Spin spinning={initialState?.loading} fullscreen />
          </ConfigProvider>
        </ProConfigProvider>
      );
    },
  };
};

/**
 * @name request 配置，可以配置错误处理
 * 它基于 axios 和 ahooks 的 useRequest 提供了一套统一的网络请求和错误处理方案。
 * @doc https://umijs.org/docs/max/request#配置
 */

// 配置拦截器
export const request: RequestConfig = {
  timeout: 30000,
  baseURL: '/api/biz',
  errorConfig: {
    errorHandler: (error: any) => {
      if (error.msg) {
        message.destroy();
        message.error(error.msg);
      }
    },
  },
  requestInterceptors: [
    (config: any) => {
      // 全局token配置
      const token = localStorage.getItem('token') ?? '';
      config.headers.token = token;
      return config;
    },
  ],
  responseInterceptors: [
    [
      (res: any) => {
        if (res.data.code !== 200 && res.data.msg) {
          return Promise.reject(res.data);
        }
        let success = false;
        if (res.data.code === 200) {
          success = true;
        }
        res.data.success = success;
        return res;
      },
    ],
  ],
};
